/**
 * 仪表盘相关 API
 */

import request from './request'

/**
 * 获取仪表盘统计数据
 */
export async function getDashboardStats() {
  try {
    // 并发请求所有统计数据
    const [products, carousels, categories, contactMessages, pendingOrders] = await Promise.all([
      request.get('/products-integrated/', { params: { page: 1, page_size: 1 } }),
      request.get('/carousels/', { params: { page: 1, page_size: 1 } }),
      request.get('/products-integrated/categories/'),
      request.get('/contact-messages/stats/'),
      request.get('/orders/', {
        params: {
          page: 1,
          page_size: 1,
          status: 'processing'
        }
      })
    ])

    // Axios 响应拦截器已经提取了 response.data
    // 所以 products, carousels, categories 直接就是数据
    const productsData = products || {}
    const carouselsData = carousels || {}
    const categoriesData = categories || []
    const contactMessagesData = contactMessages || {}

    // 轮播图也有 count 字段，直接使用
    const carouselCount = carouselsData.count || (carouselsData.results || []).length
    const pendingOrdersCount = pendingOrders?.count || 0

    return {
      totalProducts: productsData.count || 0,
      totalCarousels: carouselCount,
      categories: categoriesData,
      totalMessages: contactMessagesData.total || 0,
      unreadMessages: contactMessagesData.unread || 0,
      pendingOrders: pendingOrdersCount
    }
  } catch (error) {
    console.error('Failed to get dashboard stats:', error)
    return {
      totalProducts: 0,
      totalCarousels: 0,
      categories: [],
      totalMessages: 0,
      unreadMessages: 0,
      pendingOrders: 0
    }
  }
}

/**
 * 获取最近的产品列表
 */
export async function getRecentProducts(limit = 5) {
  try {
    const data = await request.get('/products-integrated/', {
      params: {
        page: 1,
        page_size: limit,
        ordering: '-created_at'
      }
    })
    // Axios 拦截器已经提取了 response.data
    return data?.results || []
  } catch (error) {
    console.error('Failed to get recent products:', error)
    return []
  }
}

/**
 * 获取分类产品统计
 * 通过获取所有产品并统计不同分类的数量
 */
export async function getCategoryStats() {
  try {
    // 获取所有产品（只需要第一页用于获取总数）
    const data = await request.get('/products-integrated/', {
      params: {
        page: 1,
        page_size: 100 // 获取足够多的产品来统计
      }
    })

    // Axios 拦截器已经提取了 response.data
    const products = data?.results || []
    
    // 统计各分类数量 - categories_data 是数组，产品可以属于多个分类
    const dogCount = products.filter((p: any) => 
      p?.categories_data?.some((cat: any) => cat.slug === 'dog')
    ).length
    const catCount = products.filter((p: any) => 
      p?.categories_data?.some((cat: any) => cat.slug === 'cat')
    ).length

    return [
      { category: 'dog', count: dogCount },
      { category: 'cat', count: catCount }
    ]
  } catch (error) {
    console.error('Failed to get category stats:', error)
    return [
      { category: 'dog', count: 0 },
      { category: 'cat', count: 0 }
    ]
  }
}
